/*
|-------------------------------------------------------------------------------
| 基于token验证机制的微信小程序授权模块
|-------------------------------------------------------------------------------
*/

const Auth = {}

/**
 * 获取当前登陆用户的openid
 * @return {string}
 */
Auth.openid = function () {
  const openid = wx.getStorageSync('_USER_OPENID')
    if( openid ) {
      return openid
    } else if( Auth.user() ) {
      return Auth.user().openid
    } else {
      return ''
    }
}

/**
 * 获取当前登陆用户信息
 * @return {object}
 */
Auth.user = function () {
  return wx.getStorageSync('user');
}

/**
 * 获取token
 * @return {string}
 */
Auth.token = function () {
  return wx.getStorageSync('token');
}

/**
 * 判断token还是否在有效期内
 * @return {boolean}
 */
Auth.check = function () {
  if (Auth.user() && Date.now() < wx.getStorageSync('expired_in') && Auth.token()) {
    console.log('access_token过期时间：', (wx.getStorageSync('expired_in') - Date.now()) / 1000, '秒');
    return true;
  } else {
    return false;
  }
}

/**
 * 登陆
 * @return {Promise} 用户
 */
Auth.login = function () {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        //console.log('code', res.code);
        resolve(res);
      },

      fail: function (err) {
        reject(err);
      }
    });
  });
}

/**
 * 注销
 * @return {boolean}
 */
Auth.logout = function () {
  wx.removeStorageSync('user')
  wx.removeStorageSync('token')
  wx.removeStorageSync('expired_in')
  return true
}

/**
 * 通过 wx.getUserProfile 获取 encryptedData, iv
 * @return {object}
 */
Auth.getUserProfile = function( ) {
  return new Promise(function(resolve, reject) {
      wx.getUserProfile({
          desc: "用于完善会员基本信息",
          success: function(res){
              let args = {}
              args.iv = encodeURIComponent(res.iv);
              args.encryptedData = encodeURIComponent(res.encryptedData);
              resolve(args);
          },
          fail: function(err) {
              reject(err);
          }
      });
  });
}

/**
 * 获取授权登录加密数据
 * @return {Promise} 授权信息
 */
Auth.getUserInfo = function() {
  return new Promise(function(resolve, reject) {
      Auth.getUserProfile().then(data => {
          let args = {}
          args.iv = data.iv;
          args.encryptedData = data.encryptedData;
          Auth.login().then(res => {
            args.code = res.code
            resolve(args);
          })
          .catch(err => {
            reject(err);
          })
      })
      .catch(err => {
          console.log(err)
          wx.hideLoading()
      })
  });
}

module.exports = Auth